<!-- 实习管理 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" :breadCrumb="breadCrumb"> </PageHeaderNew>
      <!-- <div class="ggg">
      <HumenNumberCard :list="list" :layout="'horizontal'" />
      <HumenNumberCard
        :list="list1"
        v-model:select-key="key1"
        color="#409Eff"
        :font-size="10"
      />
      <HumenNumberCard
        :list="list2"
        v-model:select-key="key2"
        :font-size="10"
      />
      <HumenNumberCard
        :list="list3"
        v-model:select-key="key3"
        :font-size="10"
      />
    </div> -->
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space size="large">
          <a-select
            placeholder="请选择组织"
            :default-value="1"
            :style="{ width: '200px' }"
          >
            <a-option :value="1">全部</a-option>
            <a-option>Shanghai</a-option>
            <a-option>Guangzhou</a-option>
            <a-option disabled>Disabled</a-option>
          </a-select>
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="搜索员工名字/工号"
          />
        </a-space>
      </template>
      <template #right>
        <a-space size="medium">
          <a-button type="outline">
            <template #icon>
              <icon-upload />
            </template>
            <template #default> 导出</template>
          </a-button>

          <a-dropdown
            @select="batchOperation"
            @popup-visible-change="handleBatchVisible"
            v-model:popup-visible="showBatch"
          >
            <a-button type="outline">批量操作 </a-button>
            <template #content>
              <a-doption :value="1">批量开具证明</a-doption>
              <a-doption :value="2">批量转试用期</a-doption>
              <a-doption :value="3">批量转正式员工</a-doption>
              <a-doption :value="4">批量实习变更</a-doption>
              <a-doption :value="5">批量实习结束</a-doption>
              <a-doption :value="6">批量实习评价</a-doption>
            </template>
          </a-dropdown>
        </a-space>
      </template>
    </ConditionBox>
    <TableTurn
      :tableData="getTableData"
      :args="args"
      ref="tableRef"
      :isShowPagination="false"
    >
      <a-table-column :width="60" title="序号">
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <TableControlShow
        :selectedHeader="selectedHeader"
        :showCtlCodeArr="showCtlCodeArr"
      />
      <a-table-column
        :width="200"
        dataIndex="name"
        title="评价状态"
        fixed="right"
      >
        <template #cell="{ record }">
          <span
            :class="{
              'text-gray':
                record.evaluateStatus === 0 || record.evaluateStatus === 1,
              'text-orange': record.evaluateStatus === 2,
              'text-blue': record.evaluateStatus === 3,
              'text-green': record.evaluateStatus === 4
            }"
          >
            {{
              record.evaluateStatus === 0
                ? '待创建'
                : record.evaluateStatus === 1
                ? '待发起'
                : record.evaluateStatus === 2
                ? '待自评'
                : record.evaluateStatus === 3
                ? '待他评'
                : '已完成'
            }}
          </span>
        </template></a-table-column
      >
      <a-table-column :width="200" title="操作" fixed="right">
        <template #title>
          <a-tooltip content="是否显示排序">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
              @click="isFilter"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-space>
            <a-button type="text" @click="sendEva(record.id)"
              >发起实习评价</a-button
            >
            <a-tooltip content="查看详情">
              <icon-font
                type="icon-details-def"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer'
                }"
                @click="
                  router.push({
                    name: 'InternshipEvaluationDetail',
                    query: {
                      userId: record.id,
                      step: record.evaluateStatus + 1
                    }
                  })
                "
              />
            </a-tooltip>
            <a-tooltip content="更多操作">
              <a-dropdown @select="moreItemControl" ref="tableMethodRef">
                <icon-font
                  type="icon-more-def"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
                <template #content>
                  <a-doption
                    :value="{
                      record,
                      type: 1
                    }"
                    >开具实习证明</a-doption
                  >
                  <a-doption
                    :value="{
                      record,
                      type: 2
                    }"
                    >转试用期</a-doption
                  >
                  <a-doption
                    :value="{
                      record,
                      type: 3
                    }"
                    >转正式员工</a-doption
                  >
                  <a-doption
                    :value="{
                      record,
                      type: 4
                    }"
                    >实习期变更</a-doption
                  >
                  <a-doption
                    :value="{
                      record,
                      type: 5
                    }"
                    >实习期结束</a-doption
                  >
                </template>
              </a-dropdown>
            </a-tooltip>
          </a-space>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <FormHeaderControlSetting
    title="实习列表表头设置"
    v-model:visible="modalVisiable"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
  <!-- <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="待入职导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
  <ImportModal
    v-model:visible="importVisible"
    :func="isHeaderSetting"
    :forbidList="forbidList"
    @importSave="importSave"
    @importHeaderSave="importHeaderSave"
    title="待入职导入"
  >
  </ImportModal> -->
  <TableStateMethod
    v-model:visible="TableStateMethodVisiable"
    :type="TableStateMethodType"
    @intershipStateChange="intershipStateChange"
  >
  </TableStateMethod>
  <IntershipChange
    :prev-time="currPracticeTime"
    @intershipTimeChange="intershipTimeChange"
    v-model:visible="IntershipChangeVisiable"
  ></IntershipChange>
  <IntershipProof v-model:visible="IntershipProofVisiable" :data="currData">
  </IntershipProof>
</template>

<script lang="tsx" setup>
import { GetUserList } from '@/apis/management/user/index';
import { GetBusinessModalData } from '@/apis/controltotal';
import {
  GetPracticeList,
  ChangePratice2Probation,
  ChangePratice2Confirm,
  ChangePraticeDate,
  ChangePracticeStatus
} from '@/apis/management/personnel/changeManagement/index';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';

import {
  PostImportTemplate,
  GetHeaderSetting,
  PostHeaderSetting,
  PutHeaderSetting
} from '@/apis/management/base';
import HumenNumberCard from '@/components/HumenNumberCard/index.vue';
import { getPositionList, getFlatDept } from '@/utils/common';
import TableStateMethod from './Components/TableStateMethod/index.vue';
import IntershipChange from './Components/IntershipChange/index.vue';
import IntershipProof from './Components/IntershipProof/index.vue';
import { Message } from '@arco-design/web-vue';

const router = useRouter();
const title = '实习列表';
const breadCrumb: string[] = ['人事', '异动管理', '实习管理', '实习列表'];
let currPracticeTime = ref(''); // 当前实习时间

let tableRef = ref();

/* 储存选择表格的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});

// 新增表头
const addHeader = async () => {
  try {
    const {
      funcCtlInfos: { children }
    } = (await GetBusinessModalData({
      funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
    })) as any;

    let headerListCode: any = [];
    children.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 13,
      headerListCode: headerListCode.join(',')
    });
    getData();
  } catch (error: unknown) {
    console.log(error);
  }
};

const getTableData = async (page: any) => {
  try {
    const res = await GetPracticeList({
      ...page,
      type: 1
    });
    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

let headerSetting = ref<any>([]), // 当前的表头数据
  orginHeaderList = ref([]), // 原始的表头数据
  deptList = ref([]), // 平级部门数据
  positionList = ref([]);
// 获取其他数据
const getData = async () => {
  try {
    const userId = +(localStorage.getItem('userId') as string);
    const [headerSettingRes, deptRes, positionListRes, businessModalDataRes] =
      await Promise.all([
        // 获取人员表头
        GetHeaderSetting({
          ownerFuncType: 13,
          userId
        }),
        // 获取平级的组织数据
        getFlatDept(),
        // 获取所有职位数据
        getPositionList(),
        // 获取控件人员数据
        GetBusinessModalData({
          funcCode: 'SER_FUNCA0132DDBB9F14638815C4F0C7C476435'
        })
      ]);
    orginHeaderList.value = headerSettingRes;
    headerSetting.value = [];
    const headerChildren = businessModalDataRes.funcCtlInfos.children;
    headerChildren.forEach((child: any, index: number) => {
      headerSetting.value.push({
        collectionName: child.subDetail.cnName,
        collectionCode: child.subDetail.subCode,
        heads: child.subDetail.subRelDetail.map((subDetail: any) => {
          const isDefault = headerSettingRes.headerListCode.includes(
            subDetail.ctlCode
          );
          return {
            ...subDetail,
            isDefault
          };
        })
      });
    });
    // exportHeaderList.value = headerSetting.value;
    if (headerSettingRes.headerListCode.length < 1) {
      addHeader();
    }
    deptList.value = deptRes;
    positionList.value = positionListRes.content;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

let modalVisiable = ref(false); // 判断是否显示表头

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    modalVisiable.value = !modalVisiable.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将组织名称移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 13,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error) {
    console.log(error);
  }
};

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'C63EC32DCE9CC4BE6AC7649E23234A542',
  'C9A9EF3DFFFC84AAFB97443DEE8E5B8CC',
  'CB4163C72FA5E45D38302983E8A66801E',
  'CE183DF5A547A4728A60F9AFDF3C53194',
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'C1F5AA49A78EC4B4FBD487F4D5887E576',
  'C50267C6B8E104B0C91EDD25BCAE35609',
  'C14A4E93E33754840ADDD083163AB7C68'
];

// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 性别
    case 'CEE710BACA80445DE9A39622878DF04A2':
      return (
        <div>
          {record['CEE710BACA80445DE9A39622878DF04A2'] == 1 ? '男' : '女'}
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            deptList.value.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 职位
    case 'C7341027925C943708F3AEF98703ECC47':
      return (
        <div>
          {
            positionList.value.find(
              (item: any) =>
                item.id == record['C7341027925C943708F3AEF98703ECC47']
            )?.name
          }
        </div>
      );
    // 实习期
    case 'C14A4E93E33754840ADDD083163AB7C68':
      return (
        <div>
          {record['C14A4E93E33754840ADDD083163AB7C68']?.split(',').join(' ~ ')}
        </div>
      );
    // 出生日期、入职时间
    case 'C4869FD6FEC404979A6F73A14DFA07E78' ||
      'CC0D5415792B24BBCAD7DF5AB8A25A0AB':
      return (
        <div>
          {ctlCode == 'C4869FD6FEC404979A6F73A14DFA07E78'
            ? record['C4869FD6FEC404979A6F73A14DFA07E78']?.slice(2, -2)
            : record['CC0D5415792B24BBCAD7DF5AB8A25A0AB']?.slice(2, -2)}
        </div>
      );
    default:
      break;
  }
};

const sendEva = (id: any) => {
  router.push({
    name: 'SendIntershipEvaluation',
    query: {
      id
    }
  });
};

let showBatch = ref(false);
// 批量操作
const handleBatchVisible = () => {
  if (selectedList.value.length === 0) {
    Message.error('请先选择数据');
    showBatch.value = false;
    return;
  }
};

let IntershipProofVisiable = ref(false); // 判断实习开具证明弹出框是否显示
let IntershipChangeVisiable = ref(false); // 实习期变更弹出框
let TableStateMethodVisiable = ref(false); // 判断转正式员工、转试用期、实习期结束弹出框是否显示

/*
  // 弹出框的类型
  1 转试用期
  2 转正式员工
  3 实习期结束
*/
let TableStateMethodType = ref(0);
const batchOperation = async (type: number) => {
  if (selectedList.value.length === 0) {
    Message.error('请至少选择一项！');
    return;
  }
  switch (type) {
    // 开具实习证明
    case 1:
      IntershipProofVisiable.value = true;
      break;
    // 转试用期
    case 2:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 1;
      break;
    // 转正式员工
    case 3:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 2;
      break;
    // 实习期变更
    case 4:
      IntershipChangeVisiable.value = true;
      break;
    // 实习期结束
    case 5:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 3;
      break;
    default:
      break;
  }
};

// 员工档案详情
const details = (record) => {
  //
};

let currId = ref(0), // 储存当前选中行的id
  currData = ref({}); // 储存当前选中行的数据
// 更多表格操作
const moreItemControl = async (data: { record: any; type: number }) => {
  currId.value = data.record.id;
  switch (data.type) {
    // 开具实习证明
    case 1:
      currData.value = data.record;
      IntershipProofVisiable.value = true;
      break;
    // 转试用期
    case 2:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 1;
      break;
    // 转正式员工
    case 3:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 2;
      break;
    // 实习期变更
    case 4:
      currPracticeTime.value = data.record['C14A4E93E33754840ADDD083163AB7C68'];
      console.log(currPracticeTime.value);
      console.log(data);

      IntershipChangeVisiable.value = true;
      break;
    // 实习期结束
    case 5:
      TableStateMethodVisiable.value = true;
      TableStateMethodType.value = 3;
      break;
    default:
      break;
  }
};

// 转正式员工、实习期变更、实习期结束等弹出框自定义事件
const intershipStateChange = async (type: number) => {
  try {
    switch (type) {
      // 转试用期
      case 1:
        await ChangePracticeStatus({
          ids:
            selectedList.value.length === 0
              ? [currId.value]
              : selectedList.value,
          type: 1
        });
        refresh();
        break;
      // 转正式员工
      case 2:
        await ChangePracticeStatus({
          ids:
            selectedList.value.length === 0
              ? [currId.value]
              : selectedList.value,
          type: 2
        });
        refresh();
        break;
      // 实习期结束
      case 3:
        await ChangeHumanInductionState({
          ids:
            selectedList.value.length === 0
              ? [currId.value]
              : selectedList.value,
          type: 9
        });
        refresh();
        break;
      default:
        break;
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 实习期变更自定义事件
const intershipTimeChange = async (formData: any) => {
  try {
    await ChangePraticeDate({
      id: currId.value,
      custom: `${formData.curr.startTime},${formData.curr.endTime}`
    });
    refresh();
  } catch (error: unknown) {
    console.log(error);
  }
};

const refresh = (page?: any) => {
  tableRef.value.loadData(page);
};
</script>

<style lang="less" scoped>
.container {
  padding: 10px 20px;
  .box {
    margin-bottom: 16px;
    display: flex;
    &-item {
      width: 0;
      flex: 1;
      // width: 400px;
      // display: flex;
    }
    &-item:not(:last-child) {
      margin-right: 16px;
    }
  }
  .header {
    display: flex;
    justify-content: space-between;
    &-front {
      position: relative;
      line-height: 30px;
      margin-right: 16px;
    }
  }
  .main {
    margin-top: 20px;
  }
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
.ggg {
  display: flex;
  overflow-x: auto;
  width: 100%;
}
</style>
